<template xmlns:el-col="http://www.w3.org/1999/html">
  <div>
    命题
    <el-row style="border:1px dashed lightgray;padding:10px;border-radius: 5px;">
      <el-col :span="2" style="font-weight: bolder;padding:3px;font-size: 20px;">
        科目:
      </el-col>
      <el-col :span="4">

      </el-col>
      <el-col :span="2" style="font-weight: bolder;padding:3px;font-size: 20px;">
        题型:
      </el-col>
      <el-col :span="10">
        <!--  excel表格上传  -->
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
          accept=".xlsx"
          :on-exceed="exceed"
          :limit="1"
          :on-remove="remove"
          :http-request="uploadFile"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">1次只能上传1个xls文件，且不超过500kb</div>
        </el-upload>

      </el-col>
      <el-col :span="4">
        <el-button @click="handleUploadQuestion">确定上传</el-button>
      </el-col>
    </el-row>

    <el-row>
      <!--  上传的excel表格预览  -->
      <div class="preview-excel">
        <el-table class="listTable_ele" :data="listTable" stripe  style="width:100%">
          <el-table-column prop="subjectName" label="科目" width="200" align="center"></el-table-column>
          <el-table-column label="题型" width="200" align="center">
            <template slot-scope="scope">
              {{enumMapToString(scope.row.questionType)}}
            </template>
          </el-table-column>
          <el-table-column label="题干" width="200" align="center">
            <template slot-scope="scope">
              {{scope.row.question.question}}
            </template>
          </el-table-column>
          <el-table-column prop="answer" label="答案" width="200" align="center"></el-table-column>
          <el-table-column prop="anylize" label="答案解析" width="200" align="center"></el-table-column>
          <el-table-column label="选项列表" width="200" align="center">
            <template slot-scope="scope">
              <el-row v-for="item in scope.row.question.selections" :key="''+item.content" style="float:left;">
                {{item.item}}: {{item.content}}
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>


  </div>
</template>

<script>

  import XLSX from 'xlsx';

  export default {
    name: "index",
    data() {
      return {
        listTable:[]
      };
    },


    created(){
      if(this.$store.getters.subjects.size==0){
        this.api.__api__getAllSubjects()
          .then(data=>{
            const arr = data.data;
            const map = new Map();

            for(var subject of arr){
              console.log("subject in for is "+subject);
              map.set(subject.name,subject);
            }

            this.$store.dispatch('setSubjects',map);
          })
      }
    },

    methods: {
      //解析excel
      async uploadFile(params) {
        const _file = params.file;
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            for (let sheet in workbook.Sheets) {
              //循环读取每个文件
              const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
              //若当前sheet没有数据，则continue
              if(sheetArray.length == 0){
                continue;
              }
              console.log("读取文件");
              console.log(sheetArray);
              for(let item in sheetArray){
                let rowTable = {};
                //这里的rowTable的属性名注意要与上面表格的prop一致
                //sheetArray的属性名与上传的表格的列名一致
                let subjectName  = sheetArray[item].科目;
                rowTable.subjectName = subjectName;
                let subject = this.$store.getters.subjects.get(subjectName);
                console.log("subject="+subject);
                if(subject){
                  rowTable.subjectId = subject.id;
                }
                let questionType = sheetArray[item].题型;
                rowTable.questionType = this.stringMapToEnum(questionType);

                let answer = sheetArray[item].答案;
                if(questionType=='多选题'){
                  rowTable.answer = answer.split(",")
                }else{
                  rowTable.answer = [answer];
                }
                rowTable.anylize = sheetArray[item].答案解析;

                const keys = ["选项A","选项B","选项C","选项D","选项E","选项F","选项G","选项H"];
                let selections = [];

                for(var ky of keys){
                  console.log("key="+ky);
                  let val = sheetArray[item][ky];
                  console.log("val="+val);
                  if(val){
                    selections.push({item:ky.substring(2),content:val})
                  }
                }
                let question = sheetArray[item].题干;
                rowTable.question = { question:question,selections:selections };
                rowTable.createdBy = this.$store.getters.userId;
                this.listTable.push(rowTable)
              }
            }
          } catch (e) {
            this.$message.warning('文件类型不正确！');
          }
        };
        fileReader.readAsBinaryString(_file);
      },

      //上传1个以上文件时弹窗提示错误
      exceed: function() {
        this.$message.error("最多只能上传1个xls文件");
      },
      //删除文件
      remove() {
        this.listTable = [];
      },

      handleUploadQuestion(){
        this.api.__api__addQuestions(this.listTable)
          .then(data=>{
            this.$message.success("上传成功");
          })
      },

      stringMapToEnum(qt){
        switch (qt) {
          case '单选题': return 'S';
          case '多选题': return 'M';
          case '判断题': return 'P';
          case '填空题': return 'T';
          case '简答题': return 'J';
          default: return '';
        }
      },

      enumMapToString(e){
        switch (e) {
          case 'S': return '单选题';
          case 'M': return '多选题';
          case 'P': return '判断题';
          case 'T': return '填空题';
          case 'J': return '简答题';
          default: return '';
        }
      }




    }
  }
</script>

<style scoped>

</style>
